//
//  XKImagePicker.m
//  TestDemo
//
//  Created by Macmini2015 on 16/2/22.
//  Copyright © 2016年 Macmini2015. All rights reserved.
//

#import "HYImagePicker.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import <UIKit/UIImage.h>
#import <UIKit/UIGraphics.h>

#define G_SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width

@interface HYImagePicker ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate>

@property  (nonatomic, strong) NSTimer *timer ;

@end

@implementation HYImagePicker

- (void)showImmediatelyWith:(UIImagePickerControllerSourceType)type
{
    _type = type;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (type == UIImagePickerControllerSourceTypePhotoLibrary)
        {
            if (self.mediaType == MediaTypeImage)
            {
                [self openLocalPhoto];
            }
            else
            {
                [self openLocalVideo];
            }
        }
        else if (type == UIImagePickerControllerSourceTypeCamera)
        {
            if (self.mediaType == MediaTypeImage)
            {
                [self takePhoto];
            }
            else
            {
                [self shoot];
            }
        }
    });
    [self delayDealloc];
}



- (void)showWith:(id)delegate
{
    if (!_delegate)
    {
        self.delegate = delegate;
    }
//    NSString *strTips = @"拍照";
//    NSString *strTips2 = @"";

    UIActionSheet *actionsheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:Nil otherButtonTitles:@"拍摄",@"从手机选取", nil];
    [actionsheet showInView:self.controller.view];
    
    [self delayDealloc];
}

- (void)presentPickerViewController:(UIViewController *)controller
{
    if (self.controller)
    {
        [self.controller presentViewController:controller animated:YES completion:nil];
    }
}

//- (void)showWith:(UIImagePickerControllerSourceType)type And:(CompletePickBlock)completePickBlock
//{
//    self.completePickBlock = completePickBlock ;
//    if (type == UIImagePickerControllerSourceTypePhotoLibrary)
//    {
//        if (self.mediaType == MediaTypeImage)
//        {
//            [self openLocalPhoto];
//        }
//        else
//        {
//            [self openLocalVideo];
//        }
//    }
//    else if (type == UIImagePickerControllerSourceTypeCamera)
//    {
//        if (self.mediaType == MediaTypeImage)
//        {
//            [self takePhoto];
//        }
//        else
//        {
//            [self shoot];
//        }
//    }
//}


#pragma mark - Getter

- (UIViewController *)controller
{
    if (!_controller)
    {
        if ((self.delegate) && [self.delegate isKindOfClass:[UIViewController class]])
        {
            _controller = (UIViewController *)self.delegate;
        }
        else
        {
            _controller = nil;
            NSLog(@"未设置代理");
        }
    }
    return _controller;
}

- (id<HYImagePickerDelegate>)delegate
{
    if (!_delegate)
    {
        if (_controller)
        {
            _delegate = (id <HYImagePickerDelegate>)_controller;
        }
    }
    return _delegate;
}


#pragma mark - Delegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) //拍照
    {
//        [self takePhoto];
        if (self.mediaType == MediaTypeImage)
        {
            [self takePhoto];
        }
        else
        {
            [self shoot];
        }
    }
    else if (buttonIndex == 1) //打开本地相册
    {
//        [self openLocalPhoto];
        if (self.mediaType == MediaTypeImage)
        {
            [self openLocalPhoto];
        }
        else
        {
            [self openLocalVideo];
        }
    }
    else if (buttonIndex == 2) //取消
    {
        [self setDealloc];
    }
}


/**
 *  当选择一张图片后进入这里
 *
 *  @param picker
 *  @param info
 */
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    NSString *strType = [info objectForKey:UIImagePickerControllerMediaType];
    NSString *strPath = @"";
    MediaType type = MediaTypeImage;
    
    if ([strType isEqualToString:@"public.image"]) //当选择的类型是图片
    {
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage]; //先把图片转成NSData
        if (!image) image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        //如果是刚拍摄的照片就添加到相册中去
        if (picker.sourceType ==UIImagePickerControllerSourceTypeCamera)
        {
            //将照片保存到相册
            UIImageWriteToSavedPhotosAlbum(image, nil, nil,nil);
        }
        
        
        //关闭相册界面
        image = [self fixOrientation:image];
        
        if (_isNeedScale)
        {
           image = [self scaleFromImage:image]; //图像压缩
        }
        strPath = [self saveImage:image]; //保存图像
        type = MediaTypeImage ;
    }
    else if ([strType isEqualToString:@"public.movie"])
    {
        strPath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
        type = MediaTypeMovie ;
    }
    
    NSLog(@"%@",strPath);
    [picker dismissViewControllerAnimated:YES completion:nil]; //
    

    if ([self.delegate respondsToSelector:@selector(imagePicker:type:and:)])
    {
        [self.delegate imagePicker:self type:type and:strPath];
    }
    [self setDealloc];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil]; //
    [self setDealloc];
}



#pragma mark - Pick image

//==========================
// 开始拍照
//==========================
- (void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = _allowsEditing;
        picker.sourceType = sourceType;
        [self presentPickerViewController:picker];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"抱歉，你的设备不支持该功能！"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        [self setDealloc];
        return;
    }
}



/**
 *  摄像
 */
- (void)shoot
{
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = _allowsEditing;
        picker.sourceType = sourceType;
        picker.mediaTypes = @[@"kUTTypeMovie"];
        picker.videoQuality = UIImagePickerControllerQualityType640x480;
        if (self.controller)
        {
            [self.controller presentViewController:picker animated:YES completion:nil];
        }
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"抱歉，你的设备不支持该功能！"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        [self setDealloc];
        return;
    }
}

/**
 *  打开本地相册
 */
- (void)openLocalPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate   = self;
    picker.allowsEditing = YES;
    if (self.controller)
    {
        [self.controller presentViewController:picker animated:YES completion:nil];
    }
}


/**
 *  打开本地相册
 */
- (void)openLocalVideo
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate   = self;
    picker.allowsEditing = YES;
    picker.mediaTypes = @[(NSString *)kUTTypeMovie];
    if (self.controller)
    {
        [self.controller presentViewController:picker animated:YES completion:nil];
    }
}




#pragma mark - Image


- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,CGImageGetBitsPerComponent(aImage.CGImage), 0,CGImageGetColorSpace(aImage.CGImage),CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}


/**
 *  图像压缩
 *
 *  @param image
 *
 *  @return
 */
- (UIImage *)scaleFromImage:(UIImage *)image
{
    if (!image || image.size.width == 0)
    {
        return nil;
    }
    
    //2016年06月02日17:52:00 新的缩放方法
    if (image.size.width < G_SCREEN_WIDTH)
    {
        return image;
    }
    CGSize sizeNew = CGSizeMake(G_SCREEN_WIDTH, image.size.height /image.size.width * G_SCREEN_WIDTH);
    UIGraphicsBeginImageContext(sizeNew);  //size 为CGSize类型，即你所需要的图片尺寸
    [image drawInRect:CGRectMake(0, 0, sizeNew.width, sizeNew.height)];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;   //返回的就是已经改变的图片
    
    
    
    NSData *data = UIImagePNGRepresentation(image);
    CGFloat dataSize = data.length/1024;
    CGFloat width  = image.size.width;
    CGFloat height = image.size.height;
    CGSize size;
    
    if (dataSize<=50) //小于50k
    {
        return image;
    }
    else if (dataSize<=100) //小于100k
    {
        size = CGSizeMake(width/2.f, height/2.f);
    }
    else if (dataSize<=200) //小于200k
    {
        size = CGSizeMake(width/4.f, height/4.f);
    }
    else if (dataSize<=500) //小于500k
    {
        size = CGSizeMake(width/4.f, height/4.f);
    }
    else if (dataSize<=1000) //小于1M
    {
        size = CGSizeMake(width/6.f, height/6.f);
    }
    else if (dataSize<=2000) //小于2M
    {
        size = CGSizeMake(width/10.f, height/10.f);
    }
    else //大于2M
    {
        size = CGSizeMake(width/12.f, height/12.f);
    }
    
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    if (!newImage)
    {
        return image;
    }
    return newImage;
}

/**
 *  保存图像
 *
 *  @param image
 *
 *  @return
 */
- (NSString *)saveImage:(UIImage*)image
{
    NSData *data;
    
    if (UIImagePNGRepresentation(image) == nil)
    {
        data = UIImageJPEGRepresentation(image, 1.0);
    }
    else
    {
        data = UIImagePNGRepresentation(image);
    }
    
    //图片保存的路径
    //这里将图片放在沙盒的documents文件夹中
    NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
    [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
    
    NSString *strPath = [NSString stringWithFormat:@"/image%ld.png",(long)self.tag];
//    NSData *dataOld = [fileManager contentsAtPath:strPath];
    
    
    //得到选择后沙盒中图片的完整路径
    NSString *filePath = [[NSString alloc] initWithFormat:@"%@%@",DocumentsPath,[NSString stringWithFormat:@"/image%ld.png",(long)self.tag]];
    
    if ([fileManager fileExistsAtPath:filePath])
    {
        NSLog(@"文件已存在，删除原文件");
        [fileManager removeItemAtPath:filePath error:nil];
    }
    
    BOOL isAdd = [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:strPath] contents:data attributes:nil];
    if (!isAdd)
    {
        NSLog(@"保存失败");
    }
    
    //    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    //    PersonalInfoCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
    //    [cell.imgLogo setImage:image];
    
    //    [self.imgHeadimage setImage:image];
    
    return filePath;
}

#pragma mark - Lengthen


- (void)delayDealloc
{
    _timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(check:) userInfo:nil repeats:YES];
    [_timer fire];
}

- (void)check:(id)sender
{
//    NSLog(@"123");
}

- (void)setDealloc
{
    [self.timer invalidate];
}

- (void)dealloc
{
//    NSLog(@"dealloc");
}


@end
